package com.htgd.gardenexpo.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.htgd.gardenexpo.config.DecryptingRequestWrapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.util.ContentCachingRequestWrapper;


import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author ：hejing
 * @date ：Created in 2021/6/22 15:00
 * @description：Token拦截器类
 * @modified By：`
 * @version: 1.0
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String token = request.getHeader("access_token");
        if (token != null && !token.equals("null") && !token.equals("")) {
            boolean result = TokenUtil.verify(token);
            if (!result) {
                JSONObject json = new JSONObject();
                json.put("message", "token失效！");
                json.put("code", 401);
                response.getWriter().append(json.toJSONString());
                return false;
            }
        }else {
                JSONObject json = new JSONObject();
                json.put("message", "认证失败，未通过拦截器");
                json.put("code", 603);
                response.getWriter().append(json.toJSONString());
                return false;
        }

        return true; // 继续处理其他请求
    }

}
